﻿using System;
using System.Collections.Generic;
using System.Linq;
using Game.Util;
using UnityEngine;

namespace Framework
{

    [Serializable]
    public sealed class UIGroup : IUIGroup
    {
        public IUIGroupHelper Helper { get; private set; }
        
        public string UiGroupName { get; private set; }
        public int Depth { get; private set; }

        private ControllableStack<IUIForm> m_uiForms;
        
        public UIGroup(string uiGroupName, int depth, UIGroupHelper uiGroupHelper)
        {
            Helper = uiGroupHelper;
            UiGroupName = uiGroupName;
            Depth = depth;
            uiGroupHelper.SetDepth(depth);
            m_uiForms = new ControllableStack<IUIForm>();
        }


        public void Refresh()
        {
            for (int i = 0; i < m_uiForms.Count; i++)
            {
                (m_uiForms[i] as UIForm).uiFormLogic.OnDepthChanged(Depth,i);
            }
        }

        public void AddUIForm(IUIForm uiForm)
        {
            //放至栈顶
            m_uiForms.Push(uiForm);
        }

        public void RemoveUIForm(IUIForm uiForm)
        {
            /// todo 获得在堆栈中的位置，然后移除
            m_uiForms.Remove(uiForm);
            // m_uiForms.
            // m_uiForms.Remove(uiForm);
        }

        public IUIForm GetUIForm(int serialId)
        {
            foreach (var uiForm in m_uiForms)
            {
                if (uiForm.SerialId == serialId) return uiForm;
            }

            return null;
        }

        public IUIForm GetUIForm(string uiFormAssetName)
        {
            foreach (var uiForm in m_uiForms)
            {
                if (uiForm.UIFormAssetName == uiFormAssetName) return uiForm;
            }

            return null;
        }

        public List<IUIForm> GetUIForms(string uiFormAssetName)
        {
            List<IUIForm> ls = new List<IUIForm>();
            foreach (var uiForm in m_uiForms)
            {
                if (uiForm.UIFormAssetName == uiFormAssetName) ls.Add(uiForm);
            }

            return ls;
        }

        public void OnUpdate(float elapseSeconds, float realElapseSeconds)
        {
            foreach (var uiForm in m_uiForms)
            {
                uiForm.OnUpdate(elapseSeconds, realElapseSeconds);

            }
        }
    }

}